package com.kc.gb.device.common.properties;


import com.kc.gb.device.common.dto.CameraConfig;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.representer.Representer;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class YamlHelper {

    public static void main(String[] args) throws Exception {
        // String configPath = "./application-device.yml";
        // DeviceProperties origin = loadFromYaml(new File(configPath),DeviceProperties.class);
        // log.info("origin:{}", JSON.toJSONString(origin));
        DeviceProperties config = new DeviceProperties();
        config.setHostIP("127.0.0.1");

        List<CameraConfig> camera = new ArrayList<>();
        config.setDeviceCameraConnections(camera);

        CameraConfig conf1 = new CameraConfig();
        conf1.setIp("127.0.0.1");
        camera.add(conf1);

        CameraConfig conf2 = new CameraConfig();
        conf2.setIp("172.31.214.50");
        camera.add(conf2);

        writeObjectToYaml(DeviceProperties.class,config,new File(DeviceConfiguration.getConfigPath()));
        // flush(config,new File(DevicePropertiesHelper.configPath));
    }

    /**
     * 从 yaml 文件中加载配置
     * @param file
     * @param clazz
     * @return
     * @param <T>
     * @throws FileNotFoundException
     */
    public static <T> T loadFromYaml(File file, Class<T> clazz) throws FileNotFoundException {
        Yaml yaml = new Yaml();
        return yaml.loadAs(new FileInputStream(file), clazz);
    }

    /**
     * 将配置对象保存到文件
     * @param clazz
     * @param object
     * @param filePath
     * @param <T>
     * @throws IOException
     */
    public static<T> void writeObjectToYaml(Class<T> clazz,T object, File filePath) throws IOException {
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);

        // 配置 Representer 禁用默认标签
        Representer representer = new Representer();
        representer.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        representer.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
        representer.getPropertyUtils().setSkipMissingProperties(true); // 忽略 null 字段
        // 禁用类型标签
        representer.addClassTag(clazz, org.yaml.snakeyaml.nodes.Tag.MAP);

        // 禁用类标签输出
        Yaml yaml = new Yaml(representer,options);
        log.debug("Yaml file:{}",filePath.getAbsolutePath());
        try (FileWriter writer = new FileWriter(filePath)) {
            yaml.dump(object, writer);
        } catch (Throwable e) {
            log.error("Yaml dump error:{}",e.getMessage(),e);
            throw new RuntimeException(e.getMessage());
        }
    }
}
